package org.chen.jenkins.client.utils;

import com.alibaba.fastjson.JSONObject;
import okhttp3.*;
import org.chen.jenkins.client.entity.TfsResult;

import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * @author chensj(chensj @ winning.com.cn)
 * @date 2019-09-24 15:15
 */
public class OkHttp3Util {
    /**
     * ok3 http 客户端
     */
    private OkHttpClient okHttpClient;
    /**
     * 工具类
     */
    private static OkHttp3Util instance;
    /**
     * MEDIA_TYPE <==> Content-Type
     */
    private static final MediaType MEDIA_TYPE_JSON = MediaType.parse("application/json; charset=utf-8");
    /**
     * MEDIA_TYPE_TEXT post请求不是application/x-www-form-urlencoded的，全部直接返回，不作处理，即不会解析表单数据来放到request parameter map中。
     * 所以通过request.getParameter(name)是获取不到的。只能使用最原始的方式，读取输入流来获取
     */
    private static final MediaType MEDIA_TYPE_TEXT = MediaType.parse("application/x-www-form-urlencoded; " +
            "charset=utf-8");

    /**
     * 单例模式
     *
     * @return
     */
    public static OkHttp3Util getInstance() {

        if (instance == null) {
            synchronized (OkHttp3Util.class) {
                if (instance == null) {
                    instance = new OkHttp3Util();
                }
            }
        }
        return instance;
    }

    /**
     * 私有的构造方法
     */
    private OkHttp3Util() {
        okHttpClient = new OkHttpClient.Builder()
                .writeTimeout(5, TimeUnit.SECONDS)
                .readTimeout(5, TimeUnit.SECONDS)
                .connectTimeout(5, TimeUnit.SECONDS)
                .build();
    }


    /**
     * 发送get请求
     *
     * @param url       getUrl
     * @param headerMap header 参数
     * @return result 结果
     */
    public static String sendByGetWithHeader(String url, Map<String, String> headerMap) {
        String result;
        OkHttpClient client = getInstance().okHttpClient;
        Request request = null;
        if (headerMap == null || headerMap.size() == 0) {
            request = new Request.Builder()
                    .url(url)
                    .build();
        } else {
            Headers headers = Headers.of(headerMap);
            request = new Request.Builder()
                    .url(url)
                    .headers(headers)
                    .build();
        }

        return getResponseString(client, request);
    }

    /**
     * 获取响应的结果
     *
     * @param client  客户端
     * @param request 请求
     * @return str | null
     */
    private static String getResponseString(OkHttpClient client, Request request) {
        String result;
        Response response = null;
        try {
            response = client.newCall(request).execute();
            assert response.body() != null;
            result = response.body().string();
            return result;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 发送get请求
     *
     * @param url getUrl
     * @return result 结果
     */
    public static String sendByGetUrl(String url) {
        String result;
        OkHttpClient client = getInstance().okHttpClient;
        Request request = new Request.Builder()
                .url(url)
                .build();
        return getResponseString(client, request);
    }

    /**
     * 发送post请求，参数为json格式
     *
     * @param url  url
     * @param json 参数
     * @return result 结果
     */
    public static String sendByPostJson(String url, String json) {
        OkHttpClient client = getInstance().okHttpClient;
        RequestBody body = RequestBody.create(MEDIA_TYPE_JSON, json);
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();
        return getResponseString(client, request);
    }


    /**
     * 发送post请求，参数为map格式
     *
     * @param url    url
     * @param params 参数
     * @return result
     */
    public static String sendByPostMap(String url, Map<String, String> params) {
        OkHttpClient client = getInstance().okHttpClient;
        StringBuilder content = new StringBuilder();
        Set<Map.Entry<String, String>> entrys = params.entrySet();
        Iterator<Map.Entry<String, String>> iterator = params.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, String> entry = iterator.next();
            content.append(entry.getKey()).append("=").append(entry.getValue());
            if (iterator.hasNext()) {
                content.append("&");
            }
        }

        RequestBody requestBody = RequestBody.create(MEDIA_TYPE_TEXT, content.toString());
        Request request = new Request.Builder().url(url).post(requestBody).build();
        return getResponseString(client, request);
    }

    public static void main(String[] args) {
        Map<String, String> headerMap = new HashMap<>(8);
        headerMap.put("Content-Type", "application/x-www-form-urlencoded");
        headerMap.put("Authorization", "Basic Omw1N3BleWZxYW9jM3prYXUzeHVobm9qN3BpczZ6d3dncTczNnlwbzdscjRxNDRybjNkY2E" +
                "=");
        headerMap.put("User-Agent", "OkHttp Example");
        String result = sendByGetWithHeader("http://tfs2018-web.winning.com.cn:8080/tfs/WINNING-6.0/W" +
                ".in-MVP/_apis/git/repositories?api-version=4.1", headerMap);
        TfsResult tfsResult = JSONObject.parseObject(result, TfsResult.class);
        System.out.println(tfsResult);

    }

}
